package org.example.meetingsystem.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.meetingsystem.DTO.UpdateUserDTO;
import org.example.meetingsystem.enums.UserRole;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.example.meetingsystem.entity.User;
import org.example.meetingsystem.enums.UserStatus;
import org.example.meetingsystem.annotation.RequireAuth;
import org.example.meetingsystem.service.UserService;
import org.example.meetingsystem.util.ResponseUtil;
import org.example.meetingsystem.util.Result;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor
@Tag(name = "用户管理", description = "系统管理员对用户信息的管理操作")
public class UserController {

    private final UserService userService;

    @GetMapping("/list")
    @RequireAuth(roles = {UserRole.ADMIN})
    @Operation(summary = "获取用户列表", description = "分页获取所有用户信息，支持按用户名、角色、状态筛选")
    public Result<Page<User>> getUserList(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) UserRole role,
            @RequestParam(required = false) UserStatus status) {

        Page<User> userPage = userService.getUserList(pageNum, pageSize, username, role, status);
        return ResponseUtil.success(userPage);
    }

    @GetMapping("/{userId}")
    @RequireAuth(roles = {UserRole.ADMIN})
    @Operation(summary = "获取用户详情", description = "根据用户ID获取用户详细信息")
    public Result<User> getUserById(@PathVariable Long userId) {
        User user = userService.getUserById(userId);
        if (user == null) {
            return ResponseUtil.error("用户不存在");
        }
        return ResponseUtil.success(user);
    }

    @PutMapping("/{userId}/approve")
    @RequireAuth(roles = {UserRole.ADMIN})
    @Operation(summary = "审核用户", description = "管理员审核用户注册申请，激活用户账号")
    public Result<String> approveUser(@PathVariable Long userId) {
        User user = userService.getUserById(userId);
        if (user == null) {
            return ResponseUtil.error("用户不存在");
        }

        if (user.getStatus() != UserStatus.PENDING) {
            return ResponseUtil.error("该用户状态不允许审核操作");
        }

        userService.updateUserStatus(userId, UserStatus.ACTIVE);
        return ResponseUtil.success("用户审核通过");
    }

    @PutMapping("/{userId}/freeze")
    @RequireAuth(roles = {UserRole.ADMIN})
    @Operation(summary = "冻结用户", description = "管理员冻结用户账号，禁止用户登录和使用系统")
    public Result<String> freezeUser(@PathVariable Long userId,
                                     @RequestParam(required = false) String reason) {
        User user = userService.getUserById(userId);
        if (user == null) {
            return ResponseUtil.error("用户不存在");
        }

        if (user.getStatus() == UserStatus.FROZEN) {
            return ResponseUtil.error("用户已处于冻结状态");
        }

        userService.updateUserStatus(userId, UserStatus.FROZEN);
        return ResponseUtil.success("用户已冻结");
    }

    @PutMapping("/{userId}/unfreeze")
    @RequireAuth(roles = {UserRole.ADMIN})
    @Operation(summary = "解冻用户", description = "管理员解冻用户账号，恢复用户正常使用")
    public Result<String> unfreezeUser(@PathVariable Long userId) {
        User user = userService.getUserById(userId);
        if (user == null) {
            return ResponseUtil.error("用户不存在");
        }

        if (user.getStatus() != UserStatus.FROZEN) {
            return ResponseUtil.error("用户未处于冻结状态");
        }

        userService.updateUserStatus(userId, UserStatus.ACTIVE);
        return ResponseUtil.success("用户已解冻");
    }

    @PutMapping("/{userId}")
    @RequireAuth(roles = {UserRole.ADMIN})
    @Operation(summary = "修改用户信息", description = "管理员修改用户基本信息")
    public Result<String> updateUser(@PathVariable Long userId,
                                     @Valid @RequestBody UpdateUserDTO updateUserDTO) {
        User user = userService.getUserById(userId);
        if (user == null) {
            return ResponseUtil.error("用户不存在");
        }

        userService.updateUser(userId, updateUserDTO);
        return ResponseUtil.success("用户信息更新成功");
    }

    @DeleteMapping("/{userId}")
    @RequireAuth(roles = {UserRole.ADMIN})
    @Operation(summary = "删除用户", description = "管理员删除用户账号（逻辑删除）")
    public Result<String> deleteUser(@PathVariable Long userId) {
        User user = userService.getUserById(userId);
        if (user == null) {
            return ResponseUtil.error("用户不存在");
        }
        userService.deleteUser(userId);
        return ResponseUtil.success("用户删除成功");
    }

    @GetMapping("/pending")
    @RequireAuth(roles = {UserRole.ADMIN})
    @Operation(summary = "获取待审核用户", description = "获取所有待审核的用户注册申请")
    public Result<List<User>> getPendingUsers() {
        List<User> pendingUsers = userService.getPendingUsers();
        return ResponseUtil.success(pendingUsers);
    }

    @GetMapping("/statistics")
    @RequireAuth(roles = {UserRole.ADMIN})
    @Operation(summary = "用户统计信息", description = "获取用户数量统计信息")
    public Result<Map<String, Object>> getUserStatistics() {
        Map<String, Object> statistics = userService.getUserStatistics();
        return ResponseUtil.success(statistics);
    }
}